#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import json

import scrapy
import math

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urlencode, urllib
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class GansuJinchangPolicy(BaseTaxPolicySpider):
    name = 'gansu_linxiahz_fdzdgk_policy'
    
    province = '甘肃省'
    city: str = "临夏回族自治州"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                "DOWNLOADER_MIDDLEWARES": {
                    # "scrapy.downloadermiddlewares.useragent.UserAgentMiddleware": None,  # 为 None 失效
                    "scrapy.downloadermiddlewares.retry.RetryMiddleware": None,  # 为 None 失效
                    "components.middlewares.downloadmiddlewares.public.useragent_random.RandomUserAgentMiddleware": 550,
                    "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": 551,
                    "components.middlewares.downloadmiddlewares.public.error_collector.ErrorCollectorMiddleware": 552,
                    'components.middlewares.downloadmiddlewares.private.rs_6_middlewares.Rs6RetryMiddleware': 553,
                },
                "DOWNLOAD_TIMEOUT": 200,
                # 'CONCURRENT_REQUESTS': 1,
                # "HTTPERROR_ALLOWED_CODES": [400, 404, 500, 200, 202, 502, 412],
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['临夏回族自治州人民政府', '', 'https://www.linxia.gov.cn/lxz/zwgk/fdzdgknr/lzyj/gfxwj/index.html'],
            ['临夏州发展和改革委员会', '', 'https://www.linxia.gov.cn/lxz/zwgk/bmwj/index.html'],
            ['临夏州科学技术局', '', 'https://www.linxia.gov.cn/lxz/zwgk/bmxxgkpt/lxzkxjsj/fdzdgknr/zcfg/index.html'],
            ['临夏州科学技术局', '', 'https://www.linxia.gov.cn/lxz/zwgk/bmxxgkpt/lxzkxjsj/fdzdgknr/bmwj/index.html'],
            ['临夏州工业和信息化局', '', 'https://www.linxia.gov.cn/lxz/zwgk/bmxxgkpt/lxzgyhxxhj/fdzdgknr/zcfg/index.html'],
            ['临夏州工业和信息化局', '', 'https://www.linxia.gov.cn/lxz/zwgk/bmxxgkpt/lxzgyhxxhj/fdzdgknr/bmwj/index.html'],
            ['临夏州财政局', '', 'https://www.linxia.gov.cn/lxz/zwgk/bmxxgkpt/lxzczj/fdzdgknr/zcfg/zcwj/index.html'],
            ['临夏州财政局', '', 'https://www.linxia.gov.cn/lxz/zwgk/bmxxgkpt/lxzczj/fdzdgknr/bmwj/index.html'],
            ['临夏州乡村振兴局', '', 'https://www.linxia.gov.cn/lxz/zwgk/bmxxgkpt/lxzxczxj/fdzdgknr/zcfg/index.html'],
            ['临夏州乡村振兴局', '', 'https://www.linxia.gov.cn/lxz/zwgk/bmxxgkpt/lxzxczxj/fdzdgknr/bmwj/index.html'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_content, meta={"item": item})

    def parse_content(self, response, **kwargs):
        # url = 'https://infogate.jl.gov.cn/govsearch/jsonp/gkml_xzgf20221026.jsp?'
        meta = response.meta
        unitId_list = response.xpath(".").re(r'authorizedReadUnitId\s*[:=]+\s*"(.*?)"')
        for unitId in unitId_list[::-1]:
            script = response.xpath(f"//script[@id='{unitId}']")
            url = script.xpath("./@url").get() or '/api-gateway/jpaas-publish-server/front/page/build/unit'
            url = response.urljoin(url)
            queryData = script.xpath("./@querydata").get()
            print(queryData)
            if '查询' in queryData or '规章库列表' in queryData or '法定主动公开内容第一个栏目list' in queryData:
                break
        params = json.loads(queryData.replace("'", '"'))
        params['paramJson'] = {'pageSize': 100, 'pageNo': 1}
        temp_url = url + f'{"&" if "?" in url else "?"}{urllib.parse.urlencode(params)}'
        print(temp_url)
        meta.update({"params": params, "url": url})
        yield scrapy.Request(temp_url, callback=self.parse_list, meta=meta)

    def parse_list(self, response, **kwargs):
        meta = response.meta
        params = meta.get('params')
        prev_item = meta.get('item')
        html = scrapy.Selector(text=response.json()['data']['html'])
        # print(params)
        elem_list = html.xpath("//li | "
                               "//table//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::table[string-length(string(.))>=9] |"
                               "//tr/td/a[@class='zc_list_tit']/ancestor::tr[string-length(string(.))>=9]")
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").get()
            item['title'] = elem.xpath(""".//a[@title]/@title""").get() or elem.xpath(""".//a/text()""").get()
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("./span/text()").get() or elem.xpath("string(//td)").re_first(r"\d{4}-\d{2}-\d{2}")
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            # print(params, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if meta.get("is_next") is not False:
            total_count = int(html.xpath("//div/@count").get() or html.xpath(".").re_first(r"'count':'(\d+)'"))
            total_page = math.ceil(total_count / 100)
            print(prev_item['source'], 'total', total_count, )
            data = meta['params']
            url = meta['url']
            for page_num in range(2, total_page + 1):
                data['paramJson']['pageNo'] = str(page_num)
                temp_url = url + f'{"&" if "?" in url else "?"}{urllib.parse.urlencode(data)}'
                meta.update({'item': prev_item, 'is_next': False, "params": params, "url": url})
                yield scrapy.FormRequest(temp_url, callback=self.parse_list, meta=meta)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['park'] = self.park
        # item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl gansu_linxiahz_fdzdgk_policy".split())
